//
//  AAChartController.m
//  ChartsDemo
//
//  Created by 李光尧 on 2021/3/20.
//

#import "AAChartController.h"
#import "AAChartKit.h"

@interface AAChartController ()<AAChartViewEventDelegate>

@property(nonatomic,strong) AAChartView *aChartView;
@property(nonatomic,strong) AAChartModel *aChartModel;

@property(nonatomic,strong) AAChartView *chartView;
@property(nonatomic,strong) AAChartModel *chartModel;


@property(nonatomic,strong) AASeriesElement *element;
@property(nonatomic,strong) NSMutableArray *dataList;

@property(nonatomic,strong) UILabel *spo2Lab;
@property(nonatomic,strong) UILabel *prLab;
@property(nonatomic,strong) UILabel *piLab;
@property(nonatomic,strong) UILabel *tipsLab;
@property(nonatomic,strong) UILabel *connectLab;
@property (nonatomic,strong) UIButton *reConnectBtn;

@property (nonatomic,assign) NSInteger disConnectCount;
@property (nonatomic,strong) BabyDataAnalysis *dataAnalysis;

@end

@implementation AAChartController

-(NSMutableArray *)dataList{
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (AAChartView *)chartView{
    if (!_chartView) {
        _chartView = [[AAChartView alloc] init];
        _chartView.scrollEnabled = NO;
        _chartView.delegate = self;
        _chartView.userInteractionEnabled = NO;
    }
    return _chartView;
}

- (AAChartView *)aChartView{
    if (!_aChartView) {
        _aChartView = [[AAChartView alloc] init];
        _aChartView.scrollEnabled = NO;
        _aChartView.delegate = self;
        _aChartView.userInteractionEnabled = NO;
    }
    return _aChartView;
}

- (AAChartModel *)chartModel{
    if (!_chartModel) {
        _chartModel = [[AAChartModel alloc] init];
        _chartModel.chartType = AAChartTypeSpline; //AAChartTypeSpline  AAChartTypeArea
        _chartModel.animationDuration = [NSNumber numberWithFloat:500];
        _chartModel.animationType = AAChartAnimationEaseFromTo;
        _chartModel.xAxisReversed = YES;
        _chartModel.yAxisMin = [NSNumber numberWithInt:0];
        _chartModel.yAxisMax = [NSNumber numberWithInt:100];
        _chartModel.xAxisVisible = NO;
        _chartModel.yAxisVisible = NO;
        _chartModel.legendEnabled = NO;
        _chartModel.markerRadius = [NSNumber numberWithFloat:0.2];
        _chartModel.xAxisTickInterval = [NSNumber numberWithInt:1000];
    }
    return _chartModel;
}

- (AAChartModel *)aChartModel{
    if (!_aChartModel) {
        _aChartModel = [[AAChartModel alloc] init];
        _aChartModel.chartType = AAChartTypeArea;
        _aChartModel.animationDuration = [NSNumber numberWithFloat:500];
        _aChartModel.animationType = AAChartAnimationEaseFromTo;
        _aChartModel.xAxisReversed = YES;
        _aChartModel.yAxisMin = [NSNumber numberWithInt:0];
        _aChartModel.yAxisMax = [NSNumber numberWithInt:100];
        _aChartModel.xAxisVisible = NO;
        _aChartModel.yAxisVisible = NO;
        _aChartModel.legendEnabled = NO;
        _aChartModel.markerRadius = [NSNumber numberWithFloat:0.2];
        _aChartModel.xAxisTickInterval = [NSNumber numberWithInt:1000];
    }
    return _aChartModel;
}


- (AASeriesElement *)element{
    if (!_element) {
        _element = [[AASeriesElement alloc] init];
        _element.name = FYLocalizedString(@"oxygen_pr", @"");
    }
    return _element;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubViews];
    [self creatDataModel];
    self.dataAnalysis = [[BabyDataAnalysis alloc] init];
    self.disConnectCount = 0;
    [self getDataNotify];
}

/**
 * 设置右边的按钮
 */
- (void)createRightBtn{
    
    UIButton *right_button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 21)];
    right_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [right_button setTitle:@"重连 " forState:UIControlStateNormal];
    [right_button setTitleColor:J_ColorFromHEX(0x333333) forState:UIControlStateNormal];
    [right_button addTarget:self action:@selector(touchRightBtn) forControlEvents:UIControlEventTouchUpInside];
    right_button.titleLabel.font = [UIFont systemFontOfSize:15];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right_button];
}

- (void)touchRightBtn{
    
    self.baby.scanForPeripherals().begin();

    [self babyDelegate];

}

-(void)babyDelegate{

    WEAK_SELF;

    //设置扫描到设备的委托
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        STRONG_SELF;
        if ([self.currentPeripheral.name isEqualToString:peripheral.name]) {
            self.currentPeripheral = peripheral;
            self.baby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();

        }
       

    }];

    //设置设备连接成功委托
    [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        STRONG_SELF;
        NSLog(@"设备：%@--连接成功",peripheral.name);
        [self.baby cancelScan];
       
 
    }];
    
    //设置设备连接失败委托
    [self.baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        
        NSLog(@"设备：%@--连接失败",peripheral.name);
       
    

    }];
    

    [self.baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        STRONG_SELF;

        NSString *uuid=[NSString stringWithFormat:@"%@",service.UUID];

        if ([uuid containsString:@"FFE0"]) {

            for (CBCharacteristic *c in service.characteristics) {
                
                NSString *characteristicName=[NSString stringWithFormat:@"%@",c.UUID];
                 if([characteristicName hasPrefix:@"FFE4"]){
                     [MBProgressHUD hideHUDForView:self.view animated:YES];
                     self.currentCharacteristic=c;
                     self.currentPeripheral = peripheral;
                     [self getDataNotify];
                 }
            }
        }
    }];
        
 
}


- (void)addSubViews{
    
    [self createRightBtn];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.chartView];
    [self.chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(200);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(150);
    }];
    
    [self.view addSubview:self.aChartView];
    [self.aChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.chartView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(150);
    }];
    
    for (int i=0; i<200; i++) {
//        int r = arc4random() % 10 + 50;
        [self.dataList addObject:@(0)];
    }
    self.element.data = self.dataList;
    self.chartModel.series = @[self.element];
    [self.chartView aa_drawChartWithChartModel:self.chartModel];
    
    self.aChartModel.series = @[self.element];
    [self.aChartView aa_drawChartWithChartModel:self.aChartModel];
    
    
    self.spo2Lab = [[UILabel alloc] init];
    self.spo2Lab.text = @"SpO2: ";
    [self.view addSubview:self.spo2Lab];
    [self.spo2Lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(100);
    }];
    
    self.prLab = [[UILabel alloc] init];
    self.prLab.text = @"PR: ";
    [self.view addSubview:self.prLab];
    [self.prLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.spo2Lab.mas_bottom).offset(10);
    }];
    
    self.piLab = [[UILabel alloc] init];
    self.piLab.text = @"PI: ";
    [self.view addSubview:self.piLab];
    [self.piLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.prLab.mas_bottom).offset(10);
    }];
    
    self.tipsLab = [[UILabel alloc] init];
    [self.view addSubview:self.tipsLab];
    [self.tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.piLab.mas_bottom).offset(10);
    }];
    
    self.connectLab = [[UILabel alloc] init];
    self.connectLab.text = @"断开连接的次数 0";
    [self.view addSubview:self.connectLab];
    [self.connectLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-30);
    }];
    
    
//    [NSTimer scheduledTimerWithTimeInterval:0.6 target:self selector:@selector(creatDataModel) userInfo:nil repeats:YES];
}

- (void)creatDataModel{
    
//    NSMutableArray *temp = [NSMutableArray array];
//    int r = arc4random() % 10 + 50;
//    [temp insertObject:@(r) atIndex:0];
//    //一个屏幕最多展示6条信息
//    if (self.dataList.count>6) {
//        [self.dataList removeLastObject];
//    }
//    NSMutableArray *minArr = [NSMutableArray array];
//    [minArr addObjectsFromArray:temp];
//    [minArr addObjectsFromArray:self.dataList];
//
//    self.dataList = minArr;
//    NSLog(@"此时数据是--%@",self.dataList);
//    self.element.data = self.dataList;
//    [self.chartView aa_onlyRefreshTheChartDataWithChartModelSeries:@[self.element]];
    
    int r = arc4random() % 10 + 50;
    [self.chartView aa_addPointToChartSeriesElementWithElementIndex:0 options:@(r) redraw:YES shift:YES animation:YES];
}


#pragma mark -- AAChartView delegate
- (void)aaChartView:(AAChartView *)aaChartView moveOverEventWithMessage:(AAMoveOverEventMessageModel *)message {
    NSLog(@"🚀selected point series element name: %@",message.name);
}

- (void)getDataNotify{
    self.title = @"连接中...";
    [self.baby notify:self.currentPeripheral
           characteristic:self.currentCharacteristic
                    block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        //接收到值会进入这个方法
        if([self.currentCharacteristic.value isEqual:[NSNull null]]||self.currentCharacteristic.value==NULL){
            NSLog(@"找到了FFE4数据为空");
            return ;
        }
        NSData *bluetoothData = self.currentCharacteristic.value;
        self.title = FYLocalizedString(@"real_time", @"");
        [self.dataAnalysis anylisisDataWithData:bluetoothData :^(long bmp, long SPO2, float pi) {

            self.spo2Lab.text = [NSString stringWithFormat:@"SpO2: %ld",SPO2];
            self.prLab.text = [NSString stringWithFormat:@"PR: %ld",bmp];
            self.piLab.text = [NSString stringWithFormat:@"PI: %.1f",pi];
            
        } :^(float wareform, NSString *status,NSInteger state,NSInteger stickGraph) {
            
            self.tipsLab.text = status;
            [self.chartView aa_addPointToChartSeriesElementWithElementIndex:0 options:@(wareform) redraw:YES shift:YES animation:NO];
            [self.aChartView aa_addPointToChartSeriesElementWithElementIndex:0 options:@(wareform) redraw:YES shift:YES animation:NO];
            
        }];

    }];
    
    WEAK_SELF;
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        STRONG_SELF;
        self.disConnectCount ++;
        self.title = @"断开连接";
        self.connectLab.text = [NSString stringWithFormat:@"断开连接的次数 %ld",(long)self.disConnectCount];
        [self touchRightBtn];
        
    }];
}


@end
